package com.example.wupic.bestball;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.NetworkImageView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.transform.Result;

public class HomeFragment extends Fragment {
    RequestQueue queue=MyApplication.requestQueue;//拿到请求队列
   Logger logger=Logger.getLogger("HomeFragment");
    MyAdapter myAdapter=null;
    GridView gridView=null;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=  inflater.inflate(R.layout.fragment_home,container,false);

        gridView= view.findViewById(R.id.lib_container);//找到gridview
        //新建出适配器
        getData();//调用获取数据
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //当点击某一个九宫格的时候 的点击事件
                try {
                    JSONObject jsonObject= (JSONObject) parent.getAdapter().getItem(position);
                    Toast.makeText(getContext(),
                            jsonObject.get("t_lib_name").toString(),Toast.LENGTH_LONG).show();
                    String lib_id= jsonObject.get("t_lib_id").toString();
                    //打开新的activity
                    Intent intent=new Intent(getContext(),LibActivity.class);
                    intent.putExtra("lib_id",lib_id);//携带数据
                    startActivity(intent);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        return view;
    }

    public void  getData(){
        //1.新建一个请求
        String url="http://www.wupicheng.com:7888/user/querylibs";
        JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
               //如果数据访问成功，取出数据
                try {
                  String success=   jsonObject.get("success").toString();
                  if (success.equals("true")){
                      //做数据处理
                   JSONArray jsonArray= jsonObject.getJSONArray("libs");
                   //把数据输出到控制台
                   logger.log(Level.WARNING,jsonArray.toString());

                   myAdapter=new MyAdapter(jsonArray);//拿到适配器
                   gridView.setAdapter(myAdapter);
                  }else{
                      //提醒用户 错误 网络错误
                      Toast.makeText(getContext(),"网络访问错误",Toast.LENGTH_LONG).show();
                  }
                } catch (JSONException e) {
                    e.printStackTrace();
                    //打印volley框架的错误消息
                    Toast.makeText(getContext(),e.getLocalizedMessage(),Toast.LENGTH_LONG).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        queue.add(jsonObjectRequest);//把请求加入队列中
    }
   class MyAdapter extends BaseAdapter{
       JSONArray lists=null;//图片数组

       ImageLoader imageLoader=new ImageLoader(MyApplication.requestQueue, new BitmapCache());

       public  MyAdapter(JSONArray lists){
           this.lists=lists;
       }
       //获取元素数量
       @Override
       public int getCount() {
           return this.lists.length();
       }
       //返回某个元素
       @Override
       public Object getItem(int position) {
           Object o=null;
           try {
               o= lists.get(position);
           } catch (JSONException e) {
               e.printStackTrace();
           }
           return o;
       }
       //返回某个元素的id
       @Override
       public long getItemId(int position) {
           long o=0;
           try {
               o=Integer.parseInt((((JSONObject)lists.get(position)).get("t_lib_id")).toString());
           } catch (JSONException e) {
               e.printStackTrace();
           }
           return o;
       }
      //渲染元素 文字和图片
       @Override
       public View getView(int position, View convertView, ViewGroup parent) {
           View view=convertView;
           if(view ==null){//第一次打开界面进行全新渲染
                 //拿到渲染器，渲染布局
              view= LayoutInflater.from(getContext())
                      .inflate(R.layout.lib_item,parent,false);
              TextView textView= view.findViewById(R.id.lib_txt);//找到九宫格上的文字控件
               NetworkImageView imageView= view.findViewById(R.id.lib_img);
               //给文本控件进行赋值。
               try {
                   textView.setText(((JSONObject)lists.get(position)).get("t_lib_name").toString());
                   String url=((JSONObject)lists.get(position)).get("t_lib_url").toString();
                   //用volley框架给图片赋值
                   imageView.setDefaultImageResId(R.drawable.icon_default_lib);
                   imageView.setErrorImageResId(R.drawable.icon_default_lib);
                   imageView.setImageUrl(url,imageLoader);//加载网络图片
               } catch (JSONException e) {
                   e.printStackTrace();
               }

           }else{//界面第二次打开不需要重新渲染

           }

           return view;//返回渲染好的视图
       }
   }
}
